package com.example.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class DBManager {
    private DBHelper helper;
    private SQLiteDatabase db;
    public DBManager(Context context){
        helper=new DBHelper(context);
        db=helper.getWritableDatabase();
    }
    public void insert(String name1){
        db.beginTransaction();
        try{
            ContentValues cv=new ContentValues();
            cv.put("name",name1);
            cv.put("flag","0");
            db.insert("product","id",cv);
            db.setTransactionSuccessful();

        }finally {
            db.endTransaction();
        }
    }
    public void insert1(Thing thing){
        db.beginTransaction();
        try{
            ContentValues cv=new ContentValues();
            cv.put("name",thing.getName());
            cv.put("number",thing.getNumber());
            cv.put("flag",thing.getFlag());
            db.insert("product1","id",cv);
            db.setTransactionSuccessful();

        }finally {
            db.endTransaction();
        }
    }
    public ArrayList Query(){
        String name="";
        String number="";
        String flag;
        ArrayList<Thing> produList=new ArrayList<Thing>();
        Cursor c= (Cursor) db.query("product",null,null,null,null,null,null);
        c.moveToFirst();
        while (!c.isAfterLast()){
            name=c.getString(1);
            flag=c.getString(3);
            Thing produ=new Thing(name,flag);
            produList.add(produ);
            c.moveToNext();
        }
        c.close();
        return produList;
    }
    public ArrayList Query1(){
        String name="";
        String number="";
        String flag;
        ArrayList<Thing> produList=new ArrayList<Thing>();
        Cursor c= (Cursor) db.query("product1",null,null,null,null,null,null);
        c.moveToFirst();
        while (!c.isAfterLast()){
            name=c.getString(1);
            flag=c.getString(3);
            Thing produ=new Thing(name,flag);
            produList.add(produ);
            c.moveToNext();
        }
        c.close();
        return produList;
    }


    //将标签与物品绑定
    public void Binding(String flag_num,int pos){
        ContentValues cv=new ContentValues();
        cv.put("number",flag_num);
        cv.put("flag","1");
        db.update("product",cv,"id = ?",new String[] {"pos+1"});
    }

    //删除add页面物品
    public void Delete_DB(String thingsname){
        db.execSQL("delete from product where name=?",new String[]{thingsname});
    }


}
